import random
from sys import maxint
import datetime
import os
from tempfile import TemporaryFile
import cStringIO
from pygooglechart import Axis
from pygooglechart import SimpleLineChart
from pygooglechart import GroupedVerticalBarChart

# It was important to put this 'Agg' line before the pylab import
# to avoid a memory leak when plotting over and over
# See http://mail.python.org/pipermail/python-list/2006-December/417208.html
# NOTE: If want to display, put the 'from' line before the 'Agg' line.
import matplotlib
matplotlib.use('Cairo')
from pylab import *
from dbquery import executeQuery
import random

largePlotSize = (4, 3)
color = 'b'
width = 400
height = 300

def plotSolarDay(times, totals, minTime, maxTime):
  chart = SimpleLineChart(width, height,x_range=(minTime,maxTime), y_range=(0,3000))
  chart.add_data(totals)
  chart.set_title("Watts")
  chart.set_axis_range(Axis.LEFT, 0, 3000)


  #ax.legend(('Total Power',)  )
  # xlabel('Hour')
  #ylabel('Watts')
  #ax.grid(False)
  #title('Watts')


  interval = ((len(times)/4)/2)
  
  labels = []
  for i in range(0, len(times), interval):
    labels = [times[i].strftime("%H:%M")] + labels
  chart.set_axis_labels(Axis.BOTTOM, labels)
  # set the x-axis to display hours
#  ax.xaxis.set_major_locator(HourLocator(interval= interval))
  # could use %p to get am/pm below, but too cluttered

#  ax.xaxis.set_major_formatter(hourFmt)
  return chart
    
def barChart(labels, label, points):
  chart = GroupedVerticalBarChart(width, height, y_range=(0,20))
  chart.set_title(label)
  chart.add_data(points)
  chart.set_axis_labels(Axis.BOTTOM, labels)
  chart.set_axis_range(Axis.LEFT, 0, 20)
  chart.set_bar_width(width/8.75)
  chart.set_bar_spacing(1)
  return chart
    
def drawChart(hours):
  rows = executeQuery("select time, watts from solar_agg where time" + 
  "> TIMESTAMPADD(HOUR,-%s,NOW()) and watts IS NOT NULL order by time desc" % hours)
  times = map(lambda x: x[0], rows)
  totals = map(lambda x: x[1], rows)
  return plotSolarDay(times, totals, times[-1], times[0])

  
  
def drawBarChart(type):
  if type == 'total':
    query = "select date(time), max(kwh_today) from solar_data where  time(time) > maketime(7,00,0) group by date(time) order by date(time) desc"
    label = "kWh Total"
  else:
    query = "select date(time), max(kwh_today) from solar_data where time(time) > maketime(7,00,0) and  time(time) < time(now()) group by date(time) order by date(time) desc"  
    label = "kWh at " + datetime.datetime.now().strftime("%I:%M%p")
  rows = [ x for x in reversed(executeQuery(query)[:7])]
  labels = map(lambda x: x[0].strftime("%m-%d"), rows)
  points = map(lambda x: x[1], rows)
  file = cStringIO.StringIO()
  return barChart(labels, label, points)

  
  
if __name__ == "__main__":
  chart = drawChart(18)
  print chart.get_url()
  chart.download("c.png")
  chart = drawBarChart("total")
  chart.download("t.png")
  chart = drawBarChart("daily")
  chart.download("d.png")  
